﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FPSO.Models.Domain
{
	public class logs
	{
		private string logFilePath;

		//保存至执行程序当前目录下
		public logs(string logSaveFilePath = ".\\log")
		{
			logFilePath = logFileExists(logSaveFilePath);
		}

		private static string logFileExists(string logSaveFilePath)
		{
			if (!Directory.Exists(logSaveFilePath))
			{
				// 目录不存在，创建新目录
				Directory.CreateDirectory(logSaveFilePath);
			}
			DateTime now = DateTime.Now;
			//每小时都生成一个新的文件
			string logName = $"log_{now.Year:D4}{now.Month:D2}{now.Day:D2}{now.Hour:D2}.txt";
			string filePath = Path.Combine(logSaveFilePath, logName);
			if (!File.Exists(filePath))
			{
				// 文件不存在，创建新文件
				File.Create(filePath).Close();
				string dataToWrite = $"{now} 创建文件日志文件 {logName}";
				// 将数据写入文件
				File.WriteAllText(filePath, dataToWrite + Environment.NewLine);
			}
			return filePath;

		}
		public void appendText(string txt)
		{
			// 获取文件锁
			using (var fileLock = new Mutex(false, "LogFileMutex"))
			{
				try
				{
					fileLock.WaitOne(); // 等待获取文件锁
					string logEntry = $"{DateTime.Now}: {txt}";
					// 将错误信息追加到文件末尾
					File.AppendAllText(logFilePath, logEntry + Environment.NewLine);
				}
				finally
				{
					fileLock.ReleaseMutex(); // 释放文件锁
				}
			}
		}
		public void appendExText(string exMessage, string exStackTrace = "")
		{
			// 获取文件锁
			using (var fileLock = new Mutex(false, "LogFileMutex"))
			{
				try
				{
					fileLock.WaitOne(); // 等待获取文件锁
					string logEntry = $"{DateTime.Now}: {exMessage}";
					// 将错误信息追加到文件末尾
					File.AppendAllText(logFilePath, logEntry + Environment.NewLine);
					if (exStackTrace != "")
					{
						File.AppendAllText(logFilePath, exStackTrace + Environment.NewLine);
					}
				}
				finally
				{
					fileLock.ReleaseMutex(); // 释放文件锁
				}
			}
		}
	}
}
